var monthsArray = ['','JAN','FEB','MAR','APR','MAY','JUN','JUL',
                    'AUG','SEP','OCT','NOV','DEC'];

if (typeof console == "undefined") {
    console = function() {};
    console.debug = function() {};
}

var logoutSuccess = function(event) {
    document.location = "/tmpo/";
};

var logoutError = function(event) {
    gevent = event;
    console.debug("error in logout");
};

var logoutClicked = function() {
    console.debug("logout clicked");
    jQuery.ajax({
        url:"/api/logout/",
        type:"POST",
        data:{},
        success:logoutSuccess,
        error:logoutError
    });
    return false;
};

function formatLargeNumbers(number) {
    number += '';
    x = number.split('.');
    i = x[0];
    j = x.length > 1 ? '.' + x[1] : '';
    var re = /(\d+)(\d{3})/;
    while (re.test(i)) {i = i.replace(re, '$1' + ',' + '$2');}
    return i + j;
}

var allDocReady = function() {
    $(":radio, :checkbox").css("border", "none");
    $("a.logout:contains(Logout)").click(logoutClicked);
    if ($.cookie("tmpoHome")) {
        $("img.headerLogo").parent().attr('href', $.cookie("tmpoHome"));
    }
};


function getQueryStringVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
  return false;
}

function convertMonth(monthString){
    monthString = monthString.toUpperCase();
    var i=1;
    for (i=1; i<=12; i++)
    {
        if (monthString == monthsArray[i]) {
            monthString = i;
        }
    }
    return monthString;
}

function verifyMilitaryTime(time) {
  if( time.match(
  /^[0-1]{1}[0-9]{1}[0-5]{1}[0-9]{1}$|^[2]{1}[0-3]{1}[0-5]{1}[0-9]{1}$/) ){
      time = time.substr(0,2)+":"+time.substr(2,2);
      return time;
  } 
  return false;
}

function verifyMilitaryDate(date) {
    date = date.replace(/\s*/g,"");
    var re = new RegExp(
    /^\d\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d\d\d/gi);
    var check = re.exec(date);
    if (check === null) {
        return false;
    }
    var day = date.substr(0,2);
    var month = date.substr(2,3);
    var year = date.substr(5,4);
    var output = "";
    month = convertMonth(month);
    if (month == 2 && (year%4 === 0) && day > 29) {
        return false;
    }
    if (month == 2 && (year%4 > 0) && day > 28) {
        return false;
    }
    if (((month == 4) || (month == 6) || (month == 9) || 
    (month == 11)) && day > 30) {
        return false;
    }
    if (day > 31) {
        return false;
    }   
    if (month<10) {
        month = "0"+month;
    }
    output = year+"-"+month+"-"+day;
    return output;
}

function padZero(val) {
    return (val<10) ? "0"+val : val;
}

function addzero(monthString){
	  var nothing = "";
	  (monthString > 10) ? monthString = '0' + monthString : nothing = "";
    return monthString;
}

function convertMonthNum(monthNumber){
    var i=1;
    for (i=1; i<=12; i++)
    {
        if (monthNumber == i) {
            monthNumber = monthsArray[i];
        }
    }
    return monthNumber;
}

function displayDate(dateString){
	dateString = dateString.replace(/\s*/g,"");
    var day = dateString.substr(6,2);
    var month = dateString.substr(4,2);
    var year = dateString.substr(0,4);
	var tmp ='';
	/* var displayDate ='';	*/
	var dateDisplay = "";
	for (i=1; i<=12; i++)
    {
        if (month == i) {
            tmp = monthsArray[i];
        }
    }
	dateDisplay = day + ' ' + tmp + ' ' + year;
  return dateDisplay;
}

function dateCheck(date){
    for (var i=1; i<=12; i++)
    {
        if (date == monthsArray[i]) {
            date = i;
        }
    }
    return date;
}

function validPhone(phoneString) {
    var re = new RegExp(/^\d\d\d\-\d\d\d\-\d\d\d\d/g);
    var check = re.exec(phoneString);
    if (check === null) {
        return false;
    }
    return phoneString;
}

function validPhoneThree(phoneString) {	
    var re = new RegExp(/^\d\d\d/g);
    var check = re.exec(phoneString);
    if (check === null) {
        return false;
    }
    return phoneString;
}

function validPhoneFour(phoneString) {
    var re = new RegExp(/^\d\d\d\d/g);
    var check = re.exec(phoneString);
    if (check === null) {
        return false;
    }
    return phoneString;
}

$(document).ready(allDocReady);

var fixupHtml4Pdf = function (v) {
    v = v.replace(new RegExp("<img.*>", "gim"), "");
    v = v.replace(new RegExp("<a.*>", "gim"), "");
    return v;
};

var makePrinter = function(id) {
    return function () {
        var form = document.createElement("form");
        form.action = 'http://printservice.sktdev.com/';
        form.method = "post";
        $(form).css("display", "none");
        var inp = document.createElement("input");
        inp.type = "hidden";
        inp.name = "va";
        var tag = $(id)[0].tagName;
        markup = "<" + tag + ">" + fixupHtml4Pdf( $(id).html() ) +
            "</" + tag + ">";
        inp.value = markup;
        form.appendChild(inp);
        $(document.body).append(form);
        form.submit();
    };
 // JSLint claims this return is unreachable   
 /* return false; */
};

// date output formatting
// takes a normal database ISO string, and spits out DD MMM YYYY
function militaryDate(ISOstring) {
    var output = ISOstring.replace(/:|-| /g, "").substr(6,2) + ' ' + 
        monthsArray[Number(ISOstring.replace(/:|-| /g, "").substr(4,2))] +
        ' ' + ISOstring.replace(/:|-| /g, "").substr(0,4);
    return output;
}

// time output formatting
// takes a normal database ISO string, and spits out TTTT from 0000 to 2359
function militaryTime(ISOstring) {
    var output = ISOstring.replace(/:|-| /g, "").substr(8,4);
    return output;
}

function formatTime (time) {
    if ( time < 1000 ) { time = "0"+time; }
    return time;
}

// wouldn't it be nice if we applied some function to the incoming markup and
// these regexes?
stripRe = "<ELE(?:\s[^>]*)?>(?:[^<]+|<(?!ELE(?:\s[^>]*)?>))*?</ELE>";
stripReE = function(v) {return stripRe.replace(new RegExp("ELE", "gim"), v); };
tagRe = "<ELE.*>";
